package com.wtf.dsp.admin.config;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.wtf.dsp.core.constant.NsConstant;
import org.apache.ibatis.mapping.MappedStatement;
import org.springframework.core.io.ByteArrayResource;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: CustomMybatisConfiguration
 * Description:
 * date: 2023/7/7 15:10
 *
 * @author linhuanyou
 * @version 1.0
 */
public class CustomMybatisConfiguration extends MybatisConfiguration {

    public Map<String, MappedStatement> mappedStatements(){
        return super.mappedStatements;
    }

    public void delMapperResouce(String ns , String ds, String mns, List<String> sqlIds){
        Map<String, MappedStatement> mappedStatements = super.mappedStatements;
        if(CollUtil.isEmpty(sqlIds)){
            List<String> sqlKeys = mappedStatements.keySet().stream().collect(Collectors.toList());
            for (String sqlKey : sqlKeys) {
                if(sqlKey.contains(NsConstant.mapperNamespace(ns,ds,mns))){
                    mappedStatements.remove(sqlKey);
                    int endIndex = sqlKey.lastIndexOf(".");
                    String sqlKey2 = sqlKey.substring(endIndex + 1);
                    mappedStatements.remove(sqlKey2);
                }
            }
        } else {
            for (String sqlId : sqlIds) {
                mappedStatements.remove(NsConstant.mapperNamespace(ns,ds,mns,sqlId));
                mappedStatements.remove(sqlId);
            }
        }
    }

    public void delLoadedResources(String ns , String ds, String mns){
        super.loadedResources.remove(new ByteArrayResource("".getBytes(), NsConstant.mapperNamespace(ns,ds,mns)).toString());
        delMapperResouce(ns,ds,mns,null);
    }

    public boolean containsResource(String resource){
       return super.loadedResources.contains(resource);
    }
}
